package com.mao.server.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mao.server.constant.Constants;
import com.mao.server.domain.po.User;
import com.mao.server.exception.ServiceException;
import com.mao.server.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;


@Service
public class RegisterService extends ServiceImpl<UserMapper, User> {
    @Resource
    UserMapper userMapper;

    public User selectByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.USERNAME, username);
        return getOne(queryWrapper);
    }

    public User register(User user) {
        registerPrecheck(user.getUsername(), user.getPassword());
        User dbUser = selectByUsername(user.getUsername());
        if (dbUser != null) {
            throw new ServiceException(Constants.ACCOUNT_HAS_EXIST);
        }
        if (dbUser == null) {
            user.setName(user.getUsername());
            user.setRole(user.getRole());
            userMapper.insert(user);
        }
        return user;
    }

    private void registerPrecheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            throw new ServiceException(Constants.USERNAME_OR_PASSWORD_NULL);
        }
        // 用户名不在指定范围内 错误
        if (username.length() < Constants.USERNAME_MIN_LENGTH || username.length() > Constants.USERNAME_MAX_LENGTH) {
            throw new ServiceException(Constants.USER_USERNAME_NOT_MATCH);
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < Constants.PASSWORD_MIN_LENGTH || password.length() > Constants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException(Constants.USER_PASSWORD_NOT_MATCH);
        }
    }
}
